﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using TjZheng.Framework;

namespace TjZheng.UpLoad
{
    public static class ImageExtension
    {
        /// <summary>
        /// 显示图片路径
        /// </summary>
        /// <param name="imagePath"></param>
        /// <returns></returns>
        public static string RenderImageSrc(this string imagePath)
        {
            if (imagePath.IsNull())
            {
                return "/Content/images/others/notfound.png";
            }
            return imagePath;
        }
        /// <summary>
        /// 显示图片名称
        /// </summary>
        /// <param name="imagePath"></param>
        /// <returns></returns>
        public static string RenderImageTitle(this string imagePath)
        {
            if (imagePath.IsNull())
            {
                return "NotFound";
            }
            return System.IO.Path.GetFileName(imagePath);
        }

        /// <summary>
        /// 图片预览
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="name">上传控件的Name属性</param>
        /// <param name="value">图片路径</param>
        /// <param name="htmlAttributes">图片路径</param>
        /// <returns></returns>
        public static MvcHtmlString ImagePreview(this HtmlHelper htmlHelper, string name, string value, object htmlAttributes = null)
        {
            if (name.IsNull())
            {
                return MvcHtmlString.Create("<!--对应上传控件的Name属性不能为空-->");
            }
            IDictionary<string, object> objHtmlAttributes = htmlAttributes.CreateValueDictionary();
            if (objHtmlAttributes.IsNull())
            {
                objHtmlAttributes = new Dictionary<string, object>();
            }
            object data = null;
            if (objHtmlAttributes.TryGetValue("dataoptions", out data))
            {
                objHtmlAttributes["data-options"] = string.Join(",", "position:'left',deltaX:20", objHtmlAttributes["dataoptions"]);
                objHtmlAttributes.Remove("dataoptions");
            }
            else
            {
                objHtmlAttributes["data-options"] = "position:'left',deltaX:20";
            }
            if (objHtmlAttributes.TryGetValue("class", out data))
            {
                objHtmlAttributes["class"] = string.Join(" ", "easyui-tooltip", name.Replace(".", "_"), objHtmlAttributes["class"]);
            }
            else
            {
                objHtmlAttributes["class"] = string.Format("easyui-tooltip {0}", name.Replace(".", "_"));
            }
            return MvcHtmlString.Create(string.Format("<img title=\"{0}\" onclick=\"OpenImagePreview(this);\" src=\"{1}\" {2} />", value.RenderImageTitle(), value.RenderImageSrc(), objHtmlAttributes.Select(keyvalue => string.Format("{0}=\"{1}\"", keyvalue.Key, keyvalue.Value)).JoinString(" ")));
        }
    }
}
